<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="考试名称" prop="examName">
        <el-input
          v-model="queryParams.examName"
          placeholder="请输入考试名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="评价时间" prop="classBeginDate">
        <el-date-picker
              v-model="dateRange"
              size="small"
              style="width: 240px"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option
                v-for="dict in statusOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['edu:appraiseExam:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['edu:appraiseExam:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['edu:appraiseExam:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['edu:appraiseExam:export']"
        >导出</el-button>
      </el-col>
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="appraiseExamList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!--<el-table-column label="考试ID" align="center" prop="examId" />-->
      <el-table-column label="考试名称" align="center" prop="examName" />
      <el-table-column label="总分" align="center" prop="totalScore" />
      <el-table-column label="评价开始时间" align="center" prop="startExamTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startExamTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="评价结束时间" align="center" prop="endExamTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endExamTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" :formatter="statusFormat" align="center" prop="status" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['edu:appraiseExam:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleQryQues(scope.row)"
            v-hasPermi="['edu:appraiseExam:edit']"
          >题目</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['edu:appraiseExam:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改教学评价试卷对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-tabs v-model="activeName" @tab-click="handleTabChange">
          <el-tab-pane label="基本信息" name="first">
            <el-form-item label="考试名称" prop="examName">
              <el-input v-model="form.examName" placeholder="请输入考试名称" />
            </el-form-item>
            <el-form-item label="总分" prop="totalScore">
              <el-input v-model="form.totalScore" placeholder="请输入总分" :rules="[{validator:validateDigits}]" />
            </el-form-item>
            <el-form-item label="评价开始时间" prop="startExamTime">
              <el-date-picker clearable size="small" style="width: 200px"
                v-model="form.startExamTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择评价开始时间">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="评价结束时间" prop="endExamTime">
              <el-date-picker clearable size="small" style="width: 200px"
                v-model="form.endExamTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择评价结束时间">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio
                                  v-for="dict in statusOptions"
                                  :key="dict.dictValue"
                                  :label="dict.dictValue"
                                >{{dict.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="试题" name="second">
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-input v-model="queryParams.content" type="text" placeholder="请输入题目内容" />
              </el-col>
              <el-col :span="1.5">
                <el-select v-model="queryParams.type" placeholder="请选择题目类型" clearable size="small">
                  <el-option 
                        v-for="dict in appraiseQueTypeOptions"
                        :key="dict.dictValue"
                        :label="dict.dictLabel"
                        :value="dict.dictValue" />
                </el-select>
                <el-button style="margin-left:10px" type="cyan" icon="el-icon-search" size="mini" @click="getListQue">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQueryQue">重置</el-button>
              </el-col>
            </el-row>

            <el-table ref="tableQue" v-loading="loading" :data="appraiseQueList" @selection-change="selectionChangeQueHandler">
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column label="题目类型" :formatter="appraiseQueTypeFormat" width="150" align="center" prop="type" />
              <el-table-column label="内容" align="center" prop="content" />
            </el-table>
            <pagination
              v-show="totalQue>0"
              :total="totalQue"
              :page.sync="queryParamsQue.pageNum"
              :limit.sync="queryParamsQue.pageSize"
              @pagination="getListQue"
            />
          </el-tab-pane>
        </el-tabs>
        
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="submitForm">确 定</el-button>
        <el-button size="mini" @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAppraiseExam, getAppraiseExam, delAppraiseExam, addAppraiseExam, updateAppraiseExam, exportAppraiseExam } from "@/api/edu/appraiseExam";
import { listAppraiseQue  } from "@/api/edu/appraiseQue";
import {isDigits, checkDigits} from '@/utils/validate'

export default {
  name: "AppraiseExam",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 教学评价试卷表格数据
      appraiseExamList: [],
      statusOptions: [],
      activeName: 'first',
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        examName: null,
        totalScore: null,
        status: null,
        startTime: null,
        endTime: null
      },
      appraiseQueTypeOptions: [],
      appraiseQueList: [],
      queChangeFlag: false,
      // 查询参数
      queryParamsQue: {
        pageNum: 1,
        pageSize: 10,
        content: null,
        status: '0',
        type: null
      },
      totalQue: 0,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        totalScore: [
          { required: true, message: "总分不能为空", trigger: "blur" },
        ],
        startTime: [
          { required: true, message: "评价开始时间不能为空", trigger: "blur" }
        ],
        endTime: [
          { required: true, message: "评价结束时间不能为空", trigger: "blur" }
        ]
      },
      validateDigits: (rule, value, callback) => {
        isDigits(rule, value, callback)
      },
    };
  },
  created() {
    
    this.getDicts("sys_normal_disable").then(response => {
      this.statusOptions = response.data;
    });
    this.getDicts("edu_appraise_que_type").then(response => {
      this.appraiseQueTypeOptions = response.data;
    });
    this.getList();
  },
  methods: {
    // 状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    appraiseQueTypeFormat(row, column) {
      return this.selectDictLabel(this.appraiseQueTypeOptions, row.type);
    },
    /** 查询教学评价试卷列表 */
    getList() {
      this.loading = true;
      listAppraiseExam(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.appraiseExamList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        examId: null,
        examName: null,
        totalScore: null,
        status: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        startExamTime: null,
        endExamTime: null,
        eduClassAppraiseExamQuesList: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.examId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加教学评价试卷";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const examId = row.examId || this.ids
      getAppraiseExam(examId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改教学评价试卷";
      });
    },
    handleQryQues(row) {
      this.handleUpdate(row)
      this.activeName = 'second'
      this.getListQue()
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.queChangeFlag) {
            this.queChangeFlag = false
            // form中列表全部重新赋值
            this.form.eduClassAppraiseExamQuesList = []
            for (var i1 in this.$refs.tableQue.selection) {
              this.form.eduClassAppraiseExamQuesList.push({queId: this.$refs.tableQue.selection[i1].queId})
            }
          }
          
          if(!checkDigits(this.form.totalScore)) {
            if (this.form.examId != null) {
              updateAppraiseExam(this.form).then(response => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addAppraiseExam(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          } else {
            this.msgError("总分请填写整数");
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const examIds = row.examId || this.ids;
      this.$confirm('是否确认删除教学评价试卷编号为"' + examIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delAppraiseExam(examIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有教学评价试卷数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportAppraiseExam(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    },
    handleTabChange() {
      if("second" === this.activeName) {
        this.getListQue()
      }
    },
    getListQue() {
      this.loading = true;
      listAppraiseQue(this.queryParamsQue).then(response => {
        this.appraiseQueList = response.rows;
        this.totalQue = response.total;
        this.loading = false;
        this.initQueHandler()
      });
    },
    resetQueryQue() {
      this.queryParamsQue = {
        pageNum: 1,
        pageSize: 10,
        content: null,
        status: '0',
        type: null
      }
      this.getListQue()
    },
    initQueHandler() {
      this.$nextTick(() => {
        this.appraiseQueList.forEach((item, index) => {
          if(this.form.eduClassAppraiseExamQuesList) {
            this.form.eduClassAppraiseExamQuesList.forEach(ele => {
              if(ele.queId === item.queId) {
                // 判断在返回列表中存在，就设置选中
                this.$refs.tableQue.toggleRowSelection(this.appraiseQueList[index], true)
              }
            })
          }
        })
      })
    },
    selectionChangeQueHandler(val) {
      // 保存到临时列表，提交前再设置到form表单
      // this.singleListTmp = val
      this.queChangeFlag = true
    },
  },
};
</script>
